package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import jakarta.annotation.PostConstruct;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private IVoucherOrderService voucherOrderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    //创建阻塞队列当队列为空时，消费者线程尝试取数据会被阻塞，直到队列中有新数据。
    //当队列满时，生产者线程尝试存数据会被阻塞，直到队列有空闲位置
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);

    //创建线程池
    private static  final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct//在当前类初始化之后开始执行
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucheOrderHandler());
    }

    private class VoucheOrderHandler implements Runnable{

        @Override
        public void run() {
            while(true){
                try {
                    //1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //2.创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                }

            }
        }
    }
    @Transactional
    //异步处理,不再传递给前端任何东西
    public void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户
        Long id = voucherOrder.getId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + id);
        //获取锁
        boolean isLock = lock.tryLock();
        //判断是否获取锁成功
        if(!isLock){
            //获取锁失败，返回错误或重试
            log.error("不允许重复下单");
        }
        try {
            proxy.getResult(voucherOrder);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    IVoucherOrderService proxy;
    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long id = UserHolder.getUser().getId();
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), id.toString()
        );
        //2.判断结果是否为0
        if((int)result.intValue() != 0){
            //2.1.不为0，代表没有购买资格
            return Result.fail((int)result.intValue() == 1 ? "库存不足" : "不能重复下单");
        }
        //2.2为0，有购买资格，把下单的信息保存到阻塞队列中
        long orderId = redisIdWorker.nextId("order");
        //TODO 保存阻塞队列
        //6.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(id);
        voucherOrder.setVoucherId(voucherId);
        orderTasks.add(voucherOrder);


        IVoucherOrderService proxy  = (IVoucherOrderService) AopContext.currentProxy();
        //在主线程中获取代理对象，由于获取代理对象的操作，是基于threadlocal实现的，而子线程中不能拿到threadlocal
//        voucherOrderService.getResult(voucherOrder);
        //3.返回订单id
        return Result.ok(orderId);
    }

    @Transactional
    public void getResult(VoucherOrder voucherOrder) {
        //        根据优惠券id和用户id查询订单
        Long id = voucherOrder.getUserId();

        Long count = query().eq("user_id", id).eq("voucher_id", voucherOrder.getVoucherId()).count();

        if(count >0){
            log.error("用户已经购买过一次了");
            return;
        }


        //5.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .gt("voucher_id",0)
                .update();

        if(!success){
            //扣减失败
            log.error("库存不足");
            return;
        }

        save(voucherOrder);
    }

//    @Transactional
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠券信息
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//
//
//        //2.判断秒杀是否开始
//        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
//            //尚未开始
//            return Result.fail("秒杀尚未开始");
//        }
//        //3.判断秒杀是否结束
//        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
//            //结束
//            return Result.fail("秒杀已经结束！");
//        }
//        //4.判断库存是否充足
//        if(voucher.getStock() < 1){
//            return Result.fail("库存不足");
//        }
//        Long id = UserHolder.getUser().getId();
//        //使用id可确保针对每个用户进行加锁，同一用户串行，不同用户并行
//        //创建锁对象
////        SimpleRedisLock lock = new SimpleRedisLock("order:" + id, stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order:" + id);
//        //获取锁
//        boolean isLock = lock.tryLock();
//        //判断是否获取锁成功
//        if(!isLock){
//            //获取锁失败，返回错误或重试
//            return Result.fail("一个人只允许下一单");
//        }
//        try {
//            return voucherOrderService.getResult(voucherId);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        } finally {
//            lock.unlock();
//        }
//    }


}
